package com.hankol.community

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.widget.RelativeLayout
import android.widget.TextView
import androidx.lifecycle.Observer
import androidx.recyclerview.widget.RecyclerView
import androidx.recyclerview.widget.StaggeredGridLayoutManager
import com.alibaba.android.arouter.facade.annotation.Route
import com.baselibrary.Constants
import com.baselibrary.adapter.CommonDynamicAdapter
import com.baselibrary.bean.BannerConfigListBean
import com.baselibrary.bean.DynamicInfoBean
import com.baselibrary.extension.checkNotNull
import com.baselibrary.extension.checkValue
import com.baselibrary.manager.SensorsDataManager
import com.baselibrary.router.ActivityRouter
import com.baselibrary.utils.*
import com.baselibrary.view.banner.Banner
import com.baselibrary.view.banner.BannerConfig
import com.baselibrary.view.banner.Transformer
import com.baselibrary.view.banner.loader.GlideImageLoader
import com.baselibrary.activity.BaseActivity
import com.hankol.community.adapter.HotTopicAdapter
import com.hankol.community.databinding.ActivityTopicClassifyBinding
import com.hankol.community.utils.ListUtil
import com.hankol.community.viewmodel.CommunityViewModel
import com.hankol.community.viewmodel.DynamicSearchTopicViewModel

/**
 * 话题分类（首页大改版）
 */
@Route(path = ActivityRouter.COMMUNITY.TOPIC_CLASSIFY)
class TopicClassifyActivity : BaseActivity(), View.OnClickListener {
    private lateinit var mBinding: ActivityTopicClassifyBinding
    private lateinit var mViewModel: CommunityViewModel
    private lateinit var topicModel: DynamicSearchTopicViewModel
    private val headView by lazy { LayoutInflater.from(this).inflate(R.layout.layout_topic_classify_head, null) }
    private lateinit var mFooterLayout: RelativeLayout
    private var mCurrentPage = 1
    private var channelId = 0
    private var channelName = "推荐"
    private var mCurrentCursor = "0"
    private var mIsLoadingMore = false
    private var mNoMoreData = false
    private var selectedPosition = 0
    private val mDynamicAdapter: CommonDynamicAdapter by lazy { CommonDynamicAdapter() }
    private lateinit var selectedDynamicData: DynamicInfoBean.DataBeanX.DataBean
    override fun getLayoutId(): Int {
        initImmersion(true)
        return R.layout.activity_topic_classify
    }

    override fun init() {
        setStatusBarHeight(R.color.color_F9F9F9)
        StatusBarUtil.setStatusBarDarkTheme(this, true)
        SensorsDataManager.instance.onCreateTime()
        mBinding = getDataBinding<ActivityTopicClassifyBinding>()
        mViewModel = getActivityViewModelProvider(this).get(CommunityViewModel::class.java)
        topicModel = getActivityViewModelProvider(this).get(DynamicSearchTopicViewModel::class.java)
        initData()
        initObserver()
        initListener()
        refreshData()
    }

    private fun initObserver() {
        mViewModel.bannerConfigListLD.observe(this, Observer {
            //顶部banner
            initBanner(it)
            loadHotTopic()
        })
        topicModel.searchTopicLD.observe(this, Observer {
            mBinding.llLoading.postDelayed(Runnable {
                //解决华为手机闪一下
                mBinding.llLoading.visibility = View.GONE
            }, 100)
            if (it.checkNotNull()) {
                mBinding.tvTopicContentTop.text = it[0].tagCategoryName
                val rvHotTopic = headView.findViewById<RecyclerView>(R.id.rv_hot_topic)
                val hotTopicAdapter = HotTopicAdapter()
                rvHotTopic.adapter = hotTopicAdapter
                val list = ListUtil.averageAssign(it, 3)
                hotTopicAdapter.setNewData(list)
            }
        })
        //频道页瀑布流
        mViewModel.dynamicStreamLD.observe(this, Observer {
            mBinding.srlTopicClassify.finishRefresh()
            if (it?.data != null) {
                mCurrentCursor = it.nextCursor
                if (mCurrentPage == 1) {
                    if (it.data.size == 0) {
                        mFooterLayout = layoutInflater.inflate(R.layout.layout_channel_empty_view, null) as RelativeLayout
                        mFooterLayout.findViewById<TextView>(R.id.tv_empty_tip).text = "无相关动态信息"
                        if (mDynamicAdapter.footerLayoutCount == 0) {
                            mDynamicAdapter.addFooterView(mFooterLayout)
                        }
                    } else {
                        if (mBinding.rvTopicClassify.itemDecorationCount == 0) {
                            mBinding.rvTopicClassify.addItemDecoration(StaggeredItemDecorationNew(this))
                        }
                        mDynamicAdapter.setNewData(it.data)
                        mDynamicAdapter.removeAllFooterView()
                    }
                } else {
                    mBinding.srlTopicClassify.finishLoadMore(1)
                    mIsLoadingMore = false
                    if (mDynamicAdapter != null) {
                        mDynamicAdapter.addData(it.data)
                    }
                    if (!it.isHasnext) {
                        mNoMoreData = true
                        mBinding.srlTopicClassify.finishLoadMoreWithNoMoreData()
                    }
                }
            } else {
                mNoMoreData = true
                mBinding.srlTopicClassify.finishLoadMoreWithNoMoreData()
            }
        })
        //点赞
        mViewModel.supportLiveData.observe(this, Observer { it ->
            if (it) {
                selectedDynamicData.supportNum = if (selectedDynamicData.isSupported) selectedDynamicData.supportNum.minus(1) else selectedDynamicData.supportNum.plus(1)
                selectedDynamicData.isSupported = !selectedDynamicData.isSupported
                mDynamicAdapter.notifyItemChanged(selectedPosition)
            }
        })
    }

    private fun initBanner(it: BannerConfigListBean) {
        val mBanner = headView.findViewById<Banner>(R.id.banner_topic_classify)
        val data = it.bannerConfigs
        //顶部banner
        val bannerList = arrayListOf<String>()
        for (topBannerBean in data) {
            bannerList.add(topBannerBean.img.checkValue())
        }
        it.bannerRule?.let {
            BannerSizeUtil.setBannerSizeValue(mBanner, it.wide, it.high)
        }
        mBanner.visibility = if (data.isEmpty()) View.GONE else View.VISIBLE
        mBanner?.let { banner ->
            banner.setImageLoader(GlideImageLoader(4))
            banner.setDelayTime(5000)
            banner.setBannerStyle(BannerConfig.CUSTOM_INDICATOR)
            banner.setBannerAnimation(Transformer.Default)
            banner.setIndicatorGravity(BannerConfig.CENTER)
            banner.setImages(bannerList)
            banner.setIndicatorGravity(BannerConfig.CENTER)
            banner.setOnBannerListener { position ->
                data[position].let {
                    if (!DoubleClickHelper.isOnDoubleClick()) {
                        SensorsDataManager.instance.classifyTopicBannerClick(it.name)
                        ARouterUtils.bannerJump(this, it.routeType, it.routeUrl, it.appletId)
                    }
                }
            }
            banner.start()
        }
    }

    private fun initData() {
        if (intent.extras.checkNotNull()) {
            if (ARouterUtils.parseParams(intent.extras!!, Constants.KEY_CLASSIFY_ID)[0].checkNotNull()) {
                channelId = ARouterUtils.parseParams(intent.extras!!, Constants.KEY_CLASSIFY_ID)[0].toInt()
            }
        }
        mBinding.llLoading.visibility = View.VISIBLE
        val layoutManager = StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL)
        layoutManager.gapStrategy = StaggeredGridLayoutManager.GAP_HANDLING_NONE
        mBinding.rvTopicClassify.itemAnimator = null
        mBinding.rvTopicClassify.layoutManager = layoutManager
        mBinding.rvTopicClassify.isNestedScrollingEnabled = true
        mBinding.rvTopicClassify.adapter = mDynamicAdapter
        mDynamicAdapter.addHeaderView(headView)
        mDynamicAdapter.setCallback(object : CommonDynamicAdapter.Callback {
            override fun onClickLike(position: Int, item: DynamicInfoBean.DataBeanX.DataBean) {
                selectedDynamicData = item
                selectedPosition = position
                mViewModel.reqSupport(!item.isSupported, 4, item.id)
                SensorsDataManager.instance.giveLike(selectedDynamicData.isSupported, channelName, "动态外部", SpanUtils.appendCut(selectedDynamicData.content))
            }
        })
        mDynamicAdapter.setSourceName(channelName)
        mBinding.rvTopicClassify.addOnScrollListener(object : RecyclerView.OnScrollListener() {
            override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {
                super.onScrollStateChanged(recyclerView, newState)
            }

            override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
                super.onScrolled(recyclerView, dx, dy)
                val positions = layoutManager.findLastVisibleItemPositions(null)
                //提前10个开始预加载
                if (dy > 0 && !mIsLoadingMore && positions[0] >= mDynamicAdapter.data.size - 10) {
                    mIsLoadingMore = true
                    mCurrentPage++
                    loadStream()
                }
            }
        })
        mBinding.srlTopicClassify.setOnRefreshListener { _ -> refreshData() }
        mBinding.srlTopicClassify.setOnLoadMoreListener { _ ->
            if (mIsLoadingMore) {
                return@setOnLoadMoreListener
            }
            mCurrentPage++
            loadStream()
        }
        headView.findViewById<TextView>(R.id.tv_more_topic).setOnClickListener(this)
    }

    private fun loadStream() {
        if (!mNoMoreData) {
            mViewModel.requestChannel(channelId, mCurrentPage.toString(), mCurrentCursor)
        }
    }

    private fun refreshData() {
        mCurrentPage = 1
        mCurrentCursor = "0"
        mNoMoreData = false
        mIsLoadingMore = false
        loadBanner()
        loadStream()
    }

    private fun loadBanner() {
        mViewModel.reqGetBannerConfigList(4, channelId.toLong())
    }

    fun loadHotTopic() {
        topicModel.reqSearchTopic(channelId.toLong(), 1)
    }

    private fun initListener() {
        mBinding.ivBack.setOnClickListener(this)
    }

    override fun onClick(v: View) {
        val id = v.id
        if (id == R.id.iv_back) {
            finish()
        } else if (id == R.id.tv_more_topic) {
            if (!DoubleClickHelper.isOnDoubleClick()) {
                val bundle = Bundle()
                bundle.putInt(IntentKey.DEFAULT_TOPIC_TAG_ID, channelId)
                ActivityRouter.startActivity(ActivityRouter.COMMUNITY.ALL_TOPIC, bundle)
            }
        }
    }

    override fun onPause() {
        //获取页面结束时间
        SensorsDataManager.instance.onDestroyTime()
        if (SensorsDataManager.instance.getBrowseTime() != 0L ) {
            SensorsDataManager.instance.classifyTalkView()
        }
        super.onPause()
    }

    override fun onDestroy() {
        SensorsDataManager.instance.onDestroyTime()
        if (SensorsDataManager.instance.getBrowseTime() != 0L ) {
            SensorsDataManager.instance.classifyTalkView()
        }
        super.onDestroy()
    }
}